import React from 'react';
import {inject, observer} from 'mobx-react';
import { withRouter } from 'react-router-dom';
import QueueAnim from 'rc-queue-anim';
import { List,Button,Tools, Tabs, Bubble } from 'weaver-mobile';
import { Form, CKRichText } from 'weaver-mobile-page';
import { renderLoading } from '../public';
import ParterList from './ParterList';
import QuitedList from './QuitedList';
import DefalutJoiner from './DefalutJoiner';
const getLabel = Tools.getLabel;
@withRouter
@inject('communicationStore')
@observer
export default class Create extends React.Component {
  static defaultProps = {
    prefixCls: 'cowork-communication-create',
  }

  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      pages: '', // 当前页
    };
  }

  componentWillMount(){
    const { communicationStore: { detailStore }, location: { pathname, search } } = this.props;
    const { setStoreState, createInital, clear } = detailStore;
    let params_id = (search.match(/id=(\S*)/) && search.match(/id=(\S*)/)[1]) || '';
    setStoreState({createRoutePath: pathname, id: params_id});
    if (pathname.indexOf('create') > -1) { 
      clear();
      this.setState({pages: 'create'});
      createInital();
      detailStore.setStoreState({ coworkText: '' })
    }
    if (pathname.indexOf('edit') > -1) { 
      this.setState({pages: 'edit'});
      createInital(params_id);
    }
  }

  /* 
   *  新建协作保存后路由回退
      location.pathname 当前出发地路由
      pathname 当前到底目的地路由
  */
  shouldComponentUpdate(preProps) {
    const { location: { pathname }, history } = preProps, { location } = this.props;
    if ((pathname !== location.pathname && pathname.indexOf('/createCowork') > -1 && history.action === 'POP') && pathname.indexOf('/createCowork/parterList') === -1 && location.pathname.indexOf('/createCowork/principal')=== -1 && location.pathname.indexOf('/createCowork/browser/')=== -1 && location.pathname.indexOf('/createCowork/upload/uploadFile') === -1) {
      history.go(-1);
      return false;
    }
    return true;
  }

  componentWillUnmount() {
    const { communicationStore: { detailStore } } = this.props;
    detailStore.setStoreState({createPage: 0, topKey: 'basic'});
    this.state.pages === 'edit' && detailStore.editClear()
  }

  // 跳转参与情况页面
  goAddShare = ()=>{
    const { communicationStore: { detailStore } } = this.props;
    const { itemsVo, createRoutePath } = detailStore;
    this.props.history.push(`${createRoutePath}/parterList?id=${itemsVo.id}`);
  }

  // 跳转详情页面
  goDetail = () => {
    const { communicationStore: { detailStore } } = this.props;
    const { viewCowork } = detailStore;
    viewCowork(detailStore.id);
    this.props.history.go(-1);
  }

  onBrowserChange = (key, datas) => {
    const { communicationStore: { detailStore } } = this.props;
    const { params_fileds, setStoreState } = detailStore;
    if (key) {
      params_fileds[key] = datas;
    }
    setStoreState({ params_fileds: params_fileds })
  }

  onSubmit = () => {
    const { pages } = this.state;
    const { communicationStore: { detailStore, onSearch } } = this.props;
    const { submitInfo, submitEditInfo, addInfoForm } = detailStore;
    const { principal } = addInfoForm.formParams;
    if (principal) {
      const princArr = principal.split(',');
      if (princArr.length > 5) {
        Bubble.warning(getLabel('525416', '协作负责人最多可选择5人，请重新确认负责人'));
        return;
      }
    }

    if (pages === 'edit') {
      submitEditInfo(() => {
        this.goDetail();
        onSearch(); // 编辑保存后重新刷新列表，解决待审批显示问题
      })
    } else {
      submitInfo(this.goAddShare)
    }
  }

  /* 基本信息Tab页 */
  getFields = () => {
    const { communicationStore: { detailStore } } = this.props;
    const { addInfoForm, coworkTypeInfoMap, setStoreState, getCoworkAccessory } = detailStore;
    const { conditioninfo, isInit } = addInfoForm;
    const fields = [];
    if (isInit) {
      conditioninfo.forEach((group) => {
        group.items.forEach((field) => {
          if (field.domkey[0] === "typeId") {   // 版块
            fields.push(
              <Form.Item
                key={field.domkey.join('__')}
                form={addInfoForm}
                fieldConfig={field}
                onChange={(...args) => {           
                  addInfoForm.onChange.apply(this, args);
                  setStoreState({typeId: args[1]})
                  getCoworkAccessory();
                }}
                fieldWillRender={(condition, formParams) => {  
                  let coworkTypeInfo = coworkTypeInfoMap[formParams.typeId];
                  if(coworkTypeInfo !== undefined && coworkTypeInfo.isAnonymous === "0" && condition.domkey[0] === "isAnonymous") {
                    return false;
                  }
                  if(coworkTypeInfo !== undefined && (coworkTypeInfo.allowInvite === "0"||coworkTypeInfo.allowInvite === "") && condition.domkey[0] === "allowInvite") {
                    return false;
                  }
                }}
                extra={this.state.pages === 'create' ? <div className={`${field.domkey.join('__')}-tip`}>{getLabel('525087','协作保存后，只有协作所属版块的版块负责人可修改')}</div> : ''}
              />
            );
            return;
          } else{
            fields.push(<Form.Item
              key={field.domkey.join('__')}
              form={addInfoForm}
              fieldConfig={field}
              onChange={(...args) => {            
                addInfoForm.onChange.apply(this, args);
              }}
              fieldWillRender={(condition, formParams) => {  
                let coworkTypeInfo = coworkTypeInfoMap[formParams.typeId];
                //判断允许匿名与否 
                if(coworkTypeInfo !== undefined && coworkTypeInfo.isAnonymous === "0" && condition.domkey[0] === "isAnonymous") {
                  return false;
                }
                
                if(coworkTypeInfo !== undefined && (coworkTypeInfo.allowInvite === "0"||coworkTypeInfo.allowInvite === "") && condition.domkey[0] === "allowInvite") {
                  return false;
                }
              }}
            />);
          }
        });
      });
    }
    return fields;
  }

  render(){
    const { prefixCls, communicationStore: { detailStore } } = this.props;
    const { createPage, setStoreState, addInfoForm, id, createDisabled, createRichText, coworkText, createLoading, topKey } = detailStore;
    const { pages } = this.state;
    const tabs = [
      { title: getLabel(1361, '基本信息'), topKey: 'basic' },
      { title: getLabel(16284, '详细说明'), topKey: 'detail' },
    ];
    const editTab = [
      { title: getLabel(1361, '基本信息'), topKey: 'basic' },
      { title: getLabel(16284, '详细说明'), topKey: 'detail' },
      { title: getLabel(382638, '参与范围'), topKey: 'range' },
      { title: getLabel(382659, '已退出人员'), topKey: 'quited' },
      { title: getLabel('524322', '默认参与人'), topKey: 'defaultjoin' }
    ]
    const onTabChange = (tab, index) => setStoreState({ createPage: index, topKey: tab.topKey });
    const replyProps = {
      onBrowserChange: this.onBrowserChange,
      onUploadChange: this.onBrowserChange
    }
    const config = {
      browserContextMenuOnCtrl: false,
      enableContextMenu: false,
    }
    return createLoading ? renderLoading : (
      <div className={prefixCls}>
        <Tabs 
          tabs={pages === 'edit' ? editTab : tabs} 
          onChange={onTabChange} 
          page={createPage} 
          swipeable={false}
          renderTabBar={props => <Tabs.ExpandTabBar {...props} />}
        >
          {
            topKey === 'basic' && (
              <div className={`${prefixCls}-basicInfo`}>
                <Form store={addInfoForm}>
                  <List>
                    <QueueAnim style={{overflowX: 'hidden'}}>{this.getFields()}</QueueAnim>
                  </List>
                </Form>
                <Button type="primary" onClick={this.onSubmit} disabled={createDisabled}>{getLabel(30986, '保存')}</Button>
              </div>
            )
          }
         
          <div className={`${prefixCls}-details`} style={{display: topKey === 'detail' ? 'block' : 'none' }}>
            <div className={`${prefixCls}-details-container`}>
              <CKRichText 
                store={createRichText} 
                text={coworkText}
                onChange={val => setStoreState({coworkText:val})}
                replyProps={replyProps}
                config={config}
              />
            </div>
            <Button type="primary" onClick={this.onSubmit} disabled={createDisabled}>{getLabel(30986, '保存')}</Button>
          </div>
          {pages === 'edit' && topKey === 'range' && (
            <div className={`${prefixCls}-box`}>
              <ParterList coworkId={id}/>
            </div>
          )}
          {pages === 'edit' && topKey === 'quited' && (
            <div className={`${prefixCls}-box`}>
              <QuitedList coworkId={id} />
            </div>
          )}
          {
            topKey === 'defaultjoin' && (
              <div className={`${prefixCls}-box`}>
                <DefalutJoiner isForm />
              </div>
            )
          }
        </Tabs>
     </div>    
    );
  }
}